package leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-02-09 18:40
 **/
public class LeetCode2165 {

    public long smallestNumber(long num) {
        if (num == 0) {
            return 0;
        }

        //flag: 是否为负数
        boolean flag = false;
        if (num < 0) {
            flag = true;
        }

        List<Integer> list = new ArrayList<>();
        long res = 0;
        if (flag) {
            num = -num;
            while (num != 0) {
                list.add((int) (num % 10));
                num /= 10;
            }
            list.sort((a, b) ->  b - a);
            int size = list.size();
            for (int a : list) {
                res = res * 10 + a;
            }
        } else {
            while (num != 0) {
                list.add((int) (num % 10));
                num /= 10;
            }
            Collections.sort(list);
            int zeroN = 0;
            while (list.get(zeroN) == 0) {
                ++zeroN;
            }
            res = list.get(zeroN);
            for (int i = 0; i < zeroN; i++) {
                res = res * 10;
            }
            for (int i = zeroN + 1; i < list.size(); ++i) {
                res = res * 10 + list.get(i);
            }
        }

        return flag ? -res : res;
    }


}
